<template>
  <div class="inventory-status-list-container">
    <!-- 查询表单 -->
    <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检查时间" >
        <el-date-picker clearable v-model="timeList" type="datetimerange" range-separator="~"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="盘点号" prop="inventoryId">
        <el-input
          v-model="queryForm.inventoryId"
          placeholder="请输入盘点号（可选）"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货位ID" prop="huoweiId">
        <el-input
          v-model="queryForm.huoweiId"
          placeholder="请输入货位ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品ID" prop="drugId">
        <el-input
          v-model="queryForm.drugId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编号" prop="drugCode">
        <el-input
          v-model="queryForm.drugCode"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批号" prop="drugBatchNo">
        <el-input
          v-model="queryForm.drugBatchNo"
          placeholder="请输入批号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点状态" prop="inventoryStatus">
        <el-select v-model="queryForm.inventoryStatus" placeholder="请选择盘点状态" clearable>
          <el-option label="正常盘点" value="normal"/>
          <el-option label="未盘点" value="unInventoried"/>
          <el-option label="异常" value="wrongDelivery"/>
        </el-select>
      </el-form-item>
      <el-form-item label="变更类型" prop="changeType">
        <el-select v-model="queryForm.changeType" placeholder="请选择变更类型" clearable>
          <el-option label="正常" value="正常"/>
          <el-option label="数量更改" value="数量更改"/>
          <el-option label="货位调换" value="货位调换"/>
          <el-option label="效期更改" value="效期更改"/>
          <el-option label="批号更改" value="批号更改"/>
          <el-option label="其它信息" value="其它信息"/>
        </el-select>
      </el-form-item>
      <el-form-item label="检查人" prop="userName">
        <el-input
          v-model="queryForm.userName"
          placeholder="请输入检查人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button
          type="success"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出excel
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 库存状态表格 -->
    <el-table
      v-loading="loading"
      :data="statusList"
      @selection-change="handleSelectionChange"
      :height="tableHeight"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="盘点号" align="center" prop="inventoryId"/>
      <el-table-column label="货位ID" align="center" prop="huoweiId" min-width="100"/>
      <el-table-column label="商品ID" align="center" prop="drugId" min-width="100"/>
      <el-table-column label="商品编号" align="center" prop="drugCode"/>
      <el-table-column label="商品名称" align="center" prop="drugName" min-width="150"/>
      <el-table-column label="批号" align="center" prop="drugBatchNo"/>
      <el-table-column label="库内数量" align="center" prop="sphwphQuantity">
        <template slot-scope="scope">
          <span v-if="scope.row.sphwphQuantity !== null">{{ scope.row.sphwphQuantity }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点状态" align="center" prop="inventoryStatus">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.inventoryStatus)">
            {{ scope.row.inventoryStatusDesc }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="变更类型" align="center" prop="changeType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.changeType" :type="getChangeTypeTagType(scope.row.changeType)" size="mini">
            {{ scope.row.changeType }}
          </el-tag>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="旧值" align="center" prop="oldValue"/>
      <el-table-column label="新值" align="center" prop="newValue"/>
      <el-table-column label="操作人" align="center" prop="userName"/>
      <el-table-column label="检查时间" align="center" prop="checkTime" width="160"/>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryForm.pageNum"
      :limit.sync="queryForm.pageSize"
      :page-sizes="[50, 100, 200, 500]"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {getInventoryStatusList} from '@/api/report/inventoryChange'
import Pagination from '@/components/Pagination'
import RightToolbar from '@/components/RightToolbar'

export default {
  name: 'InventoryStatusList',
  components: {
    Pagination,
    RightToolbar
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存状态表格数据
      statusList: [],
      // 表格高度
      tableHeight: 400,
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 50,
        inventoryId: '',
        huoweiId: '',
        drugId: '',
        drugCode: '',
        drugBatchNo: '',
        inventoryStatus: '',
        changeType: '',
        userName:''
      },
      timeList:[this.getDefaultStartDate(), this.getDefaultEndDate()]
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.calculateTableHeight()
    window.addEventListener('resize', this.calculateTableHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight)
  },
  methods: {
    /** 计算表格高度 */
    calculateTableHeight() {
      this.$nextTick(() => {
        // 获取窗口高度
        const windowHeight = window.innerHeight
        // 预留给其他元素的高度（表单、按钮、分页等）
        const reservedHeight = 300
        // 计算表格可用高度
        this.tableHeight = windowHeight - reservedHeight
        // 设置最小高度
        if (this.tableHeight < 300) {
          this.tableHeight = 300
        }
      })
    },
    getDefaultStartDate() {
      const date = new Date()
      date.setMonth(date.getMonth() - 1)
      return this.formatDate(date)
    },
    //获取今天的日期
    getDefaultEndDate() {
      return this.formatDate(new Date())
    },
    //格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    /** 查询库存状态列表 */
    getList() {
      this.loading = true
      if (this.timeList && this.timeList[0]) {
        this.queryForm.startTime = this.timeList[0];
      } else {
        delete this.queryForm.startTime; // 如果时间为空，则删除该字段
      }
      if (this.timeList && this.timeList[1]) {
        this.queryForm.endTime  = this.timeList[1];
      } else {
        delete this.queryForm.endTime; // 如果时间为空，则删除该字段
      }
      getInventoryStatusList(this.queryForm).then(response => {
        this.statusList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.timeList = [this.getDefaultStartDate(), this.getDefaultEndDate()];
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.drugId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('basicInfo/inventoryChange/export/inventoryStatusList', {
        ...this.queryForm
      }, `库存状态列表_${new Date().getTime()}.xlsx`)
    },

    /** 获取盘点状态标签类型 */
    getStatusTagType(status) {
      const statusMap = {
        'normal': 'success',
        'unInventoried': 'warning',
        'wrongDelivery': 'danger'
      }
      return statusMap[status] || ''
    },

    /** 获取变更类型标签类型 */
    getChangeTypeTagType(type) {
      const typeMap = {
        '正常': 'success',
        '数量更改': 'warning',
        '货位调换': 'info',
        '效期更改': 'danger',
        '批号更改': 'primary',
        '其它信息': ''
      }
      return typeMap[type] || ''
    }
  }
}
</script>

<style scoped>
.inventory-status-list-container {
  padding: 20px;
}
</style>
